package com.gzk.oeno.tech.ui.listedit;

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.Icon;
import javax.swing.JButton;
import javax.swing.JPanel;

import com.gzk.utils.CustomException;
import com.gzk.utils.data.IdObject;
import com.gzk.utils.ihm.UIUtils;


public class SingleElementPane<K, T extends IdObject<K>> extends JPanel implements ActionListener{

	private static final Icon MODIFY_ICON = UIUtils.loadSilentIcon("icons/edit_16.png");
	private static final Icon LOCK_ICON = UIUtils.loadSilentIcon("icons/lock_16.png");
	private static final Icon DELETE_ICON = UIUtils.loadSilentIcon("icons/delete_16.png");

	private T editingObject;
	private boolean isInEdition;
	private Class<? extends SingleEditionPane<T>> editor;
	private ListEditionPane<K, T> parent;

	private SingleEditionPane<T> pane;
	private JButton modifButton;
	private JButton deleteButton;

	
	public SingleElementPane(ListEditionPane<K, T> parent, Class<? extends SingleEditionPane<T>> editor, T editingObject){
		super(new BorderLayout());

		this.parent = parent;
		this.editor = editor;
		this.isInEdition = false;
		this.editingObject = editingObject;

		initGui();
	}

	private void initGui() {
		try {
			JPanel toolPanel = new JPanel(new FlowLayout());
			toolPanel.add(getModifButton());
			toolPanel.add(getDeleteButton());
			
			pane = editor.newInstance();
			pane.displayObject(editingObject, false);
			add(pane, BorderLayout.CENTER);
			add(toolPanel, BorderLayout.EAST);
			
		} catch (InstantiationException | IllegalAccessException e) {
			new CustomException("[Erreur interne] Editeur non valide", e).showException();
		}
	}

	protected JButton getModifButton() {
		if (modifButton == null){
			modifButton = new JButton(MODIFY_ICON);
			modifButton.addActionListener(this);
		}
		return modifButton;
	}

	protected JButton getDeleteButton() {
		if (deleteButton == null){
			deleteButton = new JButton(DELETE_ICON);
			deleteButton.addActionListener(this);
		}
		return deleteButton;
	}


	@Override
	public void actionPerformed(ActionEvent e) {
		if (e.getSource().equals(getModifButton())){
			try {
				if (isInEdition){
					pane.validateObject();
					editingObject = pane.getEditedObject();
					parent.wasUpdated(editingObject);
				}
				isInEdition = !isInEdition;
				updateEditionStatus();
			} catch (CustomException ex){
				ex.showException();
			}

		} else if (e.getSource().equals(getDeleteButton())){
			parent.wasDeleted(editingObject);
		}
	}

	protected void updateEditionStatus(){
		getModifButton().setIcon(isInEdition ? LOCK_ICON : MODIFY_ICON);
		pane.displayObject(editingObject, isInEdition);
	}

}
